package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class AddressBookServiceImpl implements AddressBookService {

    @Autowired
    private AddressBookMapper addressBookMapper;

    /**
     * 查询地址
     * @return
     */
    @Override
    public List<AddressBook> findAddressBooks() {
        //查询数据库
        List<AddressBook> list = addressBookMapper.findAddressBooks();
        return list;
    }

    /**
     * 新增地址
     * @param addressBook
     */
    @Override
    public void save(AddressBook addressBook) {
        Long userId = BaseContext.getCurrentId();
        addressBook.setUserId(userId);
        addressBook.setIsDefault(0);
        addressBookMapper.save(addressBook);
    }

    /**
     * 获取默认地址
     */
    @Override
    public AddressBook getDefault() {
        AddressBook addressBook = new AddressBook();
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(1);
        return addressBookMapper.getDefault(addressBook);
    }

    /**
     * 修改默认地址
     */
    @Override
    @Transactional
    public void updataStatus(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        //修改所有地址的默认地址为0
        AddressBook newAddressBook = new AddressBook();
        newAddressBook.setUserId(BaseContext.getCurrentId());
        newAddressBook.setIsDefault(0);
        addressBookMapper.updataStatus(newAddressBook);

        //修改当前地址的默认地址为1
        addressBook.setIsDefault(1);
        addressBookMapper.updataStatus(addressBook);
    }

    /**
     * 根据id查询地址
     */
    @Override
    public AddressBook getById(Long id) {
        return addressBookMapper.getById(id);
    }

    /**
     * 修改地址
     */
    @Override
    public void updateAddressBook(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.updateAddressBook(addressBook);
    }

    @Override
    public void delete(Long id) {
        Long userId = BaseContext.getCurrentId();
        addressBookMapper.delete(id, userId);
    }


}
